﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using MeterReader.Models;
using MeterReader.PubSubEvents;
using MeterReader.Services;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;

namespace MeterReader.ViewModels
{
    public class MetersDataMonitorViewModel : BindableBase
    {
        private readonly IDataService _dataService;
        private readonly IEventAggregator _eventAggregator;

        public MetersDataMonitorViewModel(IDataService dataService, IEventAggregator eventAggregator)
        {
            _dataService = dataService;
            _eventAggregator = eventAggregator;
            MeterDataCollections = _dataService.GetMeterDataCollections();
            MeterDataCollections.CollectionChanged += MeterDataCollections_CollectionChanged;
            GoHistoryCommand = new DelegateCommand<string>(Navigate);
            GoMetersCurveCommand = new DelegateCommand<string>(Navigate, (s)=>MeterDataCollections.Any());
            StartReadCommand = new DelegateCommand(StartRead, ()=> !IsStarted).ObservesProperty(() => IsStarted);
            StopReadCommand = new DelegateCommand(StopRead).ObservesCanExecute(() => IsStarted);
            _eventAggregator.GetEvent<WorkStatusChangedEvent>().Subscribe(m => IsStarted = m.IsWorking);
        }

       

        #region properties

        public ObservableCollection<MeterDataCollection> MeterDataCollections { get; set; } = new();
        private bool _isStarted = false;

        public bool IsStarted
        {
            get { return _isStarted; }
            set { SetProperty(ref _isStarted, value); }
        }

        public DelegateCommand<string> GoHistoryCommand { get; set; }
       
        public DelegateCommand<string> GoMetersCurveCommand { get; set; }
        public DelegateCommand StartReadCommand { get; set; }
        public DelegateCommand StopReadCommand { get; set; }

        #endregion properties

        private void Navigate(string obj) => _eventAggregator.GetEvent<NavigateEvent>().Publish(obj);

        private void StopRead()
        {
            _dataService!.StopPeriodicRead();
            IsStarted = false;
        }

        private void StartRead()
        {
            _dataService!.StartPeriodicRead();
            IsStarted = true;
        }

        private void MeterDataCollections_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            //通知方法canexcue
            GoMetersCurveCommand.RaiseCanExecuteChanged();
        }
        private bool CanGoMetersCurve(string arg) => MeterDataCollections.Any();
        private bool CanStartRead()=> IsStarted==false;

    }
}
